package com.tspi.log;

import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


import org.apache.commons.io.IOUtils;

public class CustomServiceLoader {

	public static final String MAPPING_CONFIG_PREFIX = "META-INF/services";

	public static Map mservices;
	
	public static <S> Map<String, Class<S>> loade(Class<S> service) throws Exception {
		String mappingConfigFile = MAPPING_CONFIG_PREFIX + "/log/" + service.getName();
		// 由于一个接口的实现类可能存在多个jar包中的META-INF目录下，所以下面使用getResources返回一个URL数组
		System.out.println("configFile:" + mappingConfigFile);
		Enumeration<URL> configFileUrls = CustomServiceLoader.class.getClassLoader().getResources(mappingConfigFile);
		if (configFileUrls == null) {
			return null;
		}
		//List<S> services = new LinkedList<S>();
		mservices = new HashMap<String, Class<S>>();

		while (configFileUrls.hasMoreElements()) {
			URL configFileUrl = configFileUrls.nextElement();
			String configContent = IOUtils.toString(configFileUrl.openStream());
			System.out.println("configContent:");
			System.out.println(configContent);
			System.out.println("configContent  --end");
			String[] serviceNames = configContent.split("\n");
			for (String serviceName : serviceNames) {
				System.out.println("serviceName: " + serviceName);
				String[] tempServiceName = serviceName.split("=");
				System.out.println("tmpServiceName:" + tempServiceName[0] + "," +tempServiceName[1]);
				
				ClassLoader classLoader = CustomServiceLoader.class.getClassLoader();
				System.out.println("classloader:" + classLoader);
				Class class1 = classLoader.loadClass(tempServiceName[1]);
				System.out.println("class1" + class1);
				
				Object serviceInstance = class1.newInstance();
				
				Logger log = (Logger)serviceInstance;
				log.warn("TEST!!!");
				//services.add((S) serviceInstance);
				mservices.put(tempServiceName[0],  serviceInstance);
			}
		}
		System.out.println("-----");
		System.out.println("mservices:" + mservices.toString());
		return mservices;
	}
	
	public static Object getType(String type) {
		System.out.println("type:" + type);
		System.out.println("-----");
		System.out.println("mservices:" + mservices.toString());
		return mservices.get(type);
	
	}

}
